package cn.im.qywx.wx.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.thymeleaf.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

/**
 * @Description: 解析XML
 */
public class AnalyzeXml {
	
	private static SAXReader reader;

	/**
	 * 读取XML工具
	 * @return
	 */
	protected static SAXReader getXmlReader() {
		return null == reader ? new SAXReader() : reader;
	}
	
	/**
	 * 发送短信
	 * @param xml
	 * @return
	 */
	public static String analyzeSMSXml(String xml){
		
		Document doc;
		Element publicEle;
		String reStr = "NOK";
		
		if(!StringUtils.isEmpty(xml)){
			try {
				doc = getXmlReader().read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
				publicEle = (Element) doc.selectSingleNode("/SERVICE/OUTPUTDATAS/RESULTCODE");
				if(null != publicEle && !StringUtils.isEmpty( publicEle.getStringValue()) && "0".equals( publicEle.getStringValue()) ){//是否有返回值
					reStr = "OK";
				}
			} catch (UnsupportedEncodingException e) {
				return reStr;
			} catch (DocumentException e) {
				return reStr;
			} 
		}
			
		return reStr;
	}
	
}
